#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简化的舆论监控工具

快速启动舆论监控功能的简化版本。
"""

import asyncio
import sys
import os

# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from sentiment.analyzer import SentimentAnalyzer
from sentiment.keywords import KeywordManager
from monitoring.monitor import SentimentMonitor, MonitorTarget
from monitoring.rules import MonitoringRules
from monitoring.alerts import AlertManager
from crawlers.douyin.web.enhanced_crawler import EnhancedDouyinCrawler

class SimpleMonitor:
    """简化的舆论监控工具"""
    
    def __init__(self):
        print("🎯 初始化舆论监控系统...")
        self.analyzer = SentimentAnalyzer()
        self.monitor = SentimentMonitor()
        self.rules = MonitoringRules()
        self.alerts = AlertManager()
        self.crawler = EnhancedDouyinCrawler()
        print("✅ 初始化完成")
    
    async def analyze_video(self, video_url: str, target_name: str = ""):
        """分析单个视频的舆情"""
        print(f"\n📺 开始分析视频: {video_url}")
        
        try:
            # 创建监控目标
            target = MonitorTarget(
                target_id=f"video_{hash(video_url)}",
                name=target_name or f"视频_{hash(video_url) % 10000}",
                url=video_url,
                platform="douyin"
            )
            
            print("🔍 获取视频信息...")
            # 这里应该调用实际的爬虫获取评论
            # 目前使用演示数据
            demo_comments = [
                "这个视频太好了！",
                "很棒的内容，学到了很多",
                "不错不错，继续加油",
                "这个太难看了吧",
                "垃圾内容，浪费时间",
                "一般般，没什么特别的"
            ]
            
            print(f"📊 分析 {len(demo_comments)} 条评论...")
            
            # 情感分析
            results = []
            for i, comment in enumerate(demo_comments):
                result = self.analyzer.analyze_text(comment)
                results.append(result)
                
                sentiment_emoji = "😊" if result.sentiment == "positive" else "😠" if result.sentiment == "negative" else "😐"
                threat_color = "🔴" if result.threat_level >= 4 else "🟡" if result.threat_level >= 2 else "🟢"
                
                print(f"  {i+1}. {sentiment_emoji} {result.sentiment.upper()} | 分数: {result.score:.3f} | 威胁: {threat_color} {result.threat_level}/5")
                print(f"     评论: {comment}")
            
            # 统计结果
            positive_count = sum(1 for r in results if r.sentiment == "positive")
            negative_count = sum(1 for r in results if r.sentiment == "negative")
            neutral_count = len(results) - positive_count - negative_count
            avg_score = sum(r.score for r in results) / len(results)
            
            print(f"\n📈 统计结果:")
            print(f"   正面评论: {positive_count} ({positive_count/len(results)*100:.1f}%)")
            print(f"   负面评论: {negative_count} ({negative_count/len(results)*100:.1f}%)")
            print(f"   中性评论: {neutral_count} ({neutral_count/len(results)*100:.1f}%)")
            print(f"   平均分数: {avg_score:.3f}")
            
            # 检查监控规则
            print(f"\n🚨 检查监控规则...")
            
            # 模拟规则检查
            if negative_count / len(results) > 0.3:  # 负面评论超过30%
                print("⚠️  触发告警: 负面评论比例过高")
                await self.send_alert(target_name, f"负面评论占比 {negative_count/len(results)*100:.1f}%")
            else:
                print("✅ 舆情正常，未触发告警")
                
            return results
            
        except Exception as e:
            print(f"❌ 分析失败: {str(e)}")
            return None
    
    async def send_alert(self, target_name: str, message: str):
        """发送告警"""
        print(f"📧 发送告警: {target_name} - {message}")
        
        # 这里可以集成实际的告警渠道
        # 比如邮件、微信、短信等
        
    def analyze_text(self, text: str):
        """分析单条文本"""
        print(f"\n📝 分析文本: {text}")
        result = self.analyzer.analyze_text(text)
        
        sentiment_emoji = "😊" if result.sentiment == "positive" else "😠" if result.sentiment == "negative" else "😐"
        threat_color = "🔴" if result.threat_level >= 4 else "🟡" if result.threat_level >= 2 else "🟢"
        
        print(f"结果: {sentiment_emoji} {result.sentiment.upper()} | 分数: {result.score:.3f} | 威胁: {threat_color} {result.threat_level}/5")
        if result.keywords:
            print(f"关键词: {', '.join(result.keywords)}")
        
        return result
    
    def show_menu(self):
        """显示菜单"""
        print("\n" + "="*50)
        print("🎯 舆论监控系统 - 简化版")
        print("="*50)
        print("1. 分析视频舆情")
        print("2. 分析单条文本")
        print("3. 查看监控统计")
        print("4. 管理关键词")
        print("5. 退出")
        print("="*50)
    
    async def interactive_mode(self):
        """交互模式"""
        while True:
            self.show_menu()
            
            try:
                choice = input("请选择功能 (1-5): ").strip()
                
                if choice == "1":
                    video_url = input("请输入视频链接: ").strip()
                    target_name = input("请输入监控目标名称 (可选): ").strip()
                    await self.analyze_video(video_url, target_name)
                    
                elif choice == "2":
                    text = input("请输入要分析的文本: ").strip()
                    if text:
                        self.analyze_text(text)
                    
                elif choice == "3":
                    print("\n📊 监控统计:")
                    print("   总监控目标: 0")
                    print("   活跃告警: 0") 
                    print("   今日分析: 0")
                    
                elif choice == "4":
                    print("\n🏷️ 关键词管理:")
                    keywords = KeywordManager()
                    print(f"   负面关键词: {len(keywords.negative_keywords)} 个")
                    print(f"   正面关键词: {len(keywords.positive_keywords)} 个")
                    print(f"   监控关键词: {len(keywords.monitor_keywords)} 个")
                    
                elif choice == "5":
                    print("👋 再见!")
                    break
                    
                else:
                    print("❌ 无效选择，请重新输入")
                    
                input("\n按 Enter 键继续...")
                
            except KeyboardInterrupt:
                print("\n👋 再见!")
                break
            except Exception as e:
                print(f"❌ 出错了: {str(e)}")
                input("按 Enter 键继续...")

async def main():
    """主函数"""
    monitor = SimpleMonitor()
    await monitor.interactive_mode()

if __name__ == "__main__":
    asyncio.run(main())